#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDateTime>
#include <QFile>
#include <QPushButton>
#include <QTimer>

#include "common/database.h"
#include "common/tool.h"

#include "dataquery.h"
#include "missionselection.h"
#include "missionsimulation.h"
#include "parameterquery.h"
#include "predictiveevaluation.h"
#include "riskanalysis.h"
#include "satellitetrack.h"
#include "stationinformation.h"
#include "voltageprediction.h"

MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_btns(new QButtonGroup(this))
    , m_timer(new QTimer(this))
{
    ui->setupUi(this);

    qInstallMessageHandler(Tool::messageHandler);

    this->showFullScreen();

    QFile qss("../res/style.css");
    qss.open(QIODevice::ReadOnly);
    this->setStyleSheet(qss.readAll());
    qss.close();

    m_timer->start(1000);
    connect(m_timer, &QTimer::timeout, this, [&]()
            { ui->labelDatetime->setText(QDateTime::currentDateTime().toString(Tool::DATETIME_FORMAT)); });

    Database::openDatabase();

    QList<QPair<QWidget*, QPushButton*>> scenes = {
        {new MissionSelection(), ui->btn_1},
        {new ParameterQuery(), ui->btn_2},
        {new DataQuery(), ui->btn_3},
        {new RiskAnalysis(), ui->btn_4},
        {new VoltagePrediction(), ui->btn_5},
        {new StationInformation(), ui->btn_6},
        {new MissionSimulation(), ui->btn_7},
        {new PredictiveEvaluation(), ui->btn_8},
        {new SatelliteTrack(), ui->btn_9},
    };

    for (int i = 0; i < scenes.size(); ++i)
    {
        ui->display->addWidget(scenes[i].first);
        m_btns->addButton(scenes[i].second, i);
    }
    connect(m_btns, &QButtonGroup::idClicked, this, [&](int id)
            { ui->display->setCurrentIndex(id); });

    connect(static_cast<MissionSelection*>(scenes[0].first), &MissionSelection::selected, ui->btn_2, &QPushButton::click);
    connect(static_cast<MissionSelection*>(scenes[0].first), &MissionSelection::selected, static_cast<ParameterQuery*>(scenes[1].first), &ParameterQuery::display);

    ui->btn_1->click();
}

MainWindow::~MainWindow()
{
    Database::closeDatabase();

    delete ui;
}
